/*------------------------------------------------------------------------------*\
**   Copyright 2008-2009 Jonhnny Weslley                                        **
**                                                                              **
**   Licensed under the Apache License, Version 2.0 (the "License");            **
**   you may not use this file except in compliance with the License.           **
**   You may obtain a copy of the License at                                    **
**                                                                              **
**       http://www.apache.org/licenses/LICENSE-2.0                             **
**                                                                              **
**   Unless required by applicable law or agreed to in writing, software        **
**   distributed under the License is distributed on an "AS IS" BASIS,          **
**   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   **
**   See the License for the specific language governing permissions and        **
**   limitations under the License.                                             **
\*------------------------------------------------------------------------------*/

package org.scalashell.util

trait StringReplacer {

  val beginToken: String
  val endToken: String

  def evaluate(text: String): String

  def replace(text: String) = {
    val buffer = new StringBuffer
    var p, s, c = 0
    var stop = false
    while (!stop && c < text.length) {
      p = text.indexOf(beginToken, c)
      if (p >= 0) {
        s = text.indexOf(endToken, p + beginToken.length)
        if (s < 0) {
          error("Missing '" + endToken + "': " + text)
        }
        val internalKey = text.substring(p + beginToken.length, s)
        buffer.append(text.substring(c, p))
        val solved = evaluate(internalKey)
        buffer.append(solved)
        c = s + endToken.length

      } else {
        stop = true
      }
    }
    buffer.append(text.substring(c))
    buffer.toString
  }

}
